﻿using System;
using System.Collections.Generic;
using System.Text;

namespace csharpcore7_ch3
{
    public class Asset
    {
        public string Name;
        public virtual decimal Liability => 0;

        static void _Main(string[] args)
        {
            Stock msft = new Stock
            {
                Name = "MSFT",
                SharesOwned = 100001
            };

            Console.WriteLine(msft.Name);       //MSFT
            Console.WriteLine(msft.SharesOwned);//1000

            House mansion = new House
            {
                Name = "Mansion",
                Mortgage = 250000
            };
            Console.WriteLine(mansion.Name);    //Mansion
            Console.WriteLine(mansion.Mortgage);//250000

            //类的多态
            Display(msft);
            Display(mansion);

            //as运算符
            Asset a = new Asset();
            Stock s = a as Stock;//s is null; no exceptoin throw
            if (s != null) Console.WriteLine(s.SharesOwned);

            // long shares = ((Stock)a).SharesOwned; //InvalidCastException.
            // long shares = (a as Stock).SharesOwned;  //NullReferenceExeption
            // 
            if (a is Stock)
                Console.WriteLine(((Stock)a).SharesOwned);

            //is运算符和模式变量(c# 7)
            if (a is Stock s1)
                Console.WriteLine(s1.SharesOwned);

            Stock s2;
            if (a is Stock)
            {
                s2 = (Stock)a;
                Console.WriteLine(s2.SharesOwned);
            }

            if (msft is Stock msft1 && msft1.SharesOwned > 100000)
                Console.WriteLine("Wealthy");
            else
                msft1 = new Stock();


            Asset housea = mansion;
            Console.WriteLine(mansion.Liability); //250000
            Console.WriteLine(housea.Liability);      //250000
        }

        /// <summary>
        /// 显示Asset类的Name属性
        /// </summary>
        /// <param name="asset"></param>
        public static void Display(Asset asset)
        {
            Console.WriteLine(asset.Name);
        }
    }
    public class Stock : Asset //inherits from Asset
    {
        public long SharesOwned;
    }
    public class House : Asset //inherits from Asset
    {
        public decimal Mortgage;
        /// <summary>
        /// 重写基类中的虚方法
        /// </summary>
        public override decimal Liability => Mortgage;
    }

   
}
